 <template>
	<div class="preview-test-paper" v-loading.fullscreen.lock="loading"
		element-loading-text="拼命加载中">
		<el-row class="preview-head" type="flex" align="middle">
			<el-col :span="2" :offset="1">
				<router-link :to="{path: '/test/intelligent-node', query: {id: $route.query.id, edit: $route.query.id}}">
					<el-button type="text"><i class="el-icon-arrow-left"></i>重新配置试卷</el-button>
				</router-link>
			</el-col>
			<el-col :span="20" align="right">
				<el-button type="primary" size="small" plain @click="setCopyTest">编辑试卷</el-button>
				<el-button type="primary" size="small"  @click="submitForm('ruleForm')">提交</el-button>
			</el-col>
		</el-row>

		<div class="preview-conten maxW">
			
			<div class="preview-conten-l">
				
				<div class="preview-conten-l-h">
					<h3>{{ruleForm.name}}</h3>
					<p>考试时间：{{ruleForm.time ? ruleForm.time : '--'}} 分钟，满分{{tatolSun}}分</p>
				</div>

				<ul>
					<template v-for="type of testList.question_type" >
						<li class="preview-conten-list" :key="type.id">
							<div class="preview-conten-title" >
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，共{{type.score}}分<span v-show="type.common">，{{type.common}}。</span>)
							</div>
							
							<!-- <div class="preview-conten-title" v-if="type.id == 1">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，只有一个符合题意的正确答案。错选，不选均不得分。)
							</div>

							<div class="preview-conten-title"  v-else-if="type.id == 2">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，有两个或两个以上符合题意的正确答案。多选、少选、错选、不选均不得分。)
							</div>

							<div class="preview-conten-title"  v-else-if="type.id == 9">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，两个答案中只有一个符合题意的正确答案。)
							</div>
							<div class="preview-conten-title"  v-else>
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，点击文本框，直接在文本框内作答即可。)
							</div> -->

							<ul class="preview-conten-subject">

								<template v-for="(item, index) of testList.question_list" v-if="parseInt(item.qt_id) === parseInt(type.id)">
									<li class="preview-conten-subject-c"  v-if="parseInt(item.type_base_id) === 1 || parseInt(item.type_base_id) === 2 || parseInt(item.type_base_id) === 4">

										<template>
											<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
										</template>
										
										<ul class="preview-topic"  >

											<template v-for="(option,index2) of item.option" >

												<li class="preview-subject-title preview-false option-pattern" v-if="item.type_base_id === 4"  :key="index2">
													<template >
														<el-checkbox disabled :label="option.name"></el-checkbox>
													</template>
												</li>

												<template v-else>
													<li class="preview-subject-title preview-false" v-if="item.pattern === 1" :key="index2">
														<template>
															<el-checkbox disabled :label="option.name"></el-checkbox>
															<div  v-html="option.value"></div>
														</template>
													</li>

													<li class="preview-subject-title preview-false option-pattern" v-if="item.pattern === 2"  :key="index2">
														<template >
															<el-checkbox disabled :label="option.name"></el-checkbox>
															<!-- <div  v-html="option.value"></div> -->
														</template>
													</li>
												</template>
												
											</template>
											
										</ul>
											

										<el-collapse accordion class="preview-answer">
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>题型：{{item.question_type}}</span>
														<span>难度： {{item.difficulty}}</span>
														<span>重点程度： 高</span>
													</div>
												</template>
												<div class="preview-accordion-answer" v-if="item.type_base_id == 1 || item.type_base_id == 2 || item.type_base_id == 4">

													<span>正确答案： </span>
													<template v-if="item.type_base_id == 4">
														<div v-if="item.answer"><i>{{item.answer[0] }}</i></div>
													</template>
													<template v-else-if="item.type_base_id == 1 || item.type_base_id == 2">
														<div><i v-for="answer of item.answer">{{answer}}</i></div>
													</template>

												</div>
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>

									<li class="preview-conten-subject-c"  v-else>

										<template>
											<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
										</template>
										
										<ul class="preview-topic">
											<li class="preview-subject-title preview-false"  v-for="(option,index2) of item.option" :key="index2">
												<template>
													<el-checkbox disabled :label="option.name"></el-checkbox>
													<div  v-html="option.value"></div>
												</template>
											</li>
										</ul>
											

										<el-collapse accordion class="preview-answer">
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>题型：{{item.question_type}}</span>
														<span>难度： {{item.difficulty}}</span>
														<span v-if="item.keynote == 1">重点程度： 低</span>
														<span v-if="item.keynote == 2">重点程度： 中</span>
														<span v-if="item.keynote == 3">重点程度： 高</span>
													</div>
												</template>
											<!-- 	<div class="preview-accordion-answer">
													<span>正确答案： </span>
													<div>
														<i v-for="answer of item.answer">{{answer}}</i>
													</div>
												</div> -->
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>
								</template>

							</ul>
						</li>
					</template>
				</ul>
			</div>

			<div class="preview-conten-r">
				<el-form :model="ruleForm" :rules="rules" ref="ruleForm"  class="preview-ruleForm">
					<el-form-item label="试卷名称"  prop="name">
						<el-input type="textarea" v-model="ruleForm.name" resize="none" maxlength= '20'  placeholder="请输入试卷名称，不超过20字"></el-input>
					</el-form-item>

					<el-form-item label="建议时长"  prop="time" >
						  <el-input-number placeholder="请输入时长" v-model="ruleForm.time" controls-position="right" :step="1" step-strictly :min="1" :max="1000"></el-input-number>分钟
					</el-form-item>

	

					<el-form-item label="分数排布" required class="preview-label">
						
						<template v-for="(item, index) of questionType">
							<el-form-item :label="`${item.name}: ${item.count}题, 每题`"  prop="single">
								  <el-input-number v-model="item.score" @change="setTotal($event, item)"  placeholder="请输入分数" controls-position="right" :step="1" step-strictly :min="0" :max="100"></el-input-number>分
							</el-form-item>
						</template>
					</el-form-item>
				</el-form>
				
			</div>
		</div>

		<el-dialog
		  title="提示"
		  :visible.sync="dialogVisible"
		  width="30%"
		  custom-class="visible-box">
		  <span>该试题已保存到 '我的卷库'</span>
		  <span slot="footer" class="dialog-footer">
		  	<a :href="downloadFiler()"  @click="dialogVisible = false">下载试题</a>
		    <el-button  @click="submitForm('ruleForm')" type="primary">转到我的卷库</el-button>
		  </span>
		</el-dialog>

		<!-- 预览图片 -->
		<image-viewer 
            v-if="imagePreview.showViewer"
            :initial-index="imageIndex"
            :on-close="closeViewer"
            :url-list="imagePreview.previewSrcList">
        </image-viewer>
		
	</div>
</template>

<script>
	
	export default {
		data(){
			return {
				imagePreview: {/*图片预览*/
					showViewer: false,
					previewSrcList: []
				},
				loading: true,
				ruleForm: {
					name: '', 		/*试卷名称*/
					time: 100, 		/*建议时长*/
					single: '', 	/*单项选择题*/
					multiple: '', 	/*多项选择题*/
					judge: '',		/*判断题*/
					answers: '',	/*问答*/
				},
				rules: {
					name: [
						{ required: true, message: '请输入试卷名称', trigger: 'blur' },
						{ min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
					],
					time: [
						{ required: true, message: '请输入建议时长', trigger: 'blur' },
					],
					// single: [
					// 	{ required: true, message: '请输入分数', trigger: 'blur' },
					// ],
					// multiple: [
					// 	{ required: true, message: '请输入分数', trigger: 'blur' },
					// ],
					// judge: [
					// 	{ required: true, message: '请输入分数', trigger: 'blur' },
					// ],
					// answers: [
					// 	{ required: true, message: '请输入分数', trigger: 'blur' },
					// ],
				},
				headClassList: null, 
				testList:[],
				intelligentObj: JSON.parse(sessionStorage.getItem('intelligentObj')), /*智能组卷携带是信息*/
				questionType: [],
				dialogVisible: false,

				imgVisible: false,
				imgArray: [],
				imgIndex: 0,

			}
		},
		created(){
			this.getTestList()
		},
		mounted(){
			/**
			 * 为当前页面创建一个自定义class类名 
			 * @type {[type]}
			 */
			this.headClassList = document.querySelector('#trunk').classList;
			this.headClassList.add('hidden-header')

			document.querySelector('.preview-conten-l').addEventListener('click',  (e)=> {
				
				let [targetSrc ,imgs, srcArr, currentIdx] = ['', '', '', '']
				if (e.target.nodeName === 'IMG') {

					this.imagePreview.showViewer = true
					targetSrc = e.target.src;
					imgs = [...e.target.parentNode.children];
					srcArr = imgs.map(item=>item.currentSrc);
					currentIdx = srcArr.indexOf(targetSrc);

					this.imagePreview.previewSrcList = srcArr
					this.imgIndex = targetSrc

				}
			
			}, false)
		},
		computed: {
			imageIndex() {
			    return this.imagePreview.previewSrcList.indexOf(this.imgIndex);
			},
			/**
			 * 计算试卷总分
			 * @DateTime 2019-08-02T15:35:44+0800
			 * @return   {[type]}                 [description]
			 */
			tatolSun(){
				let sun = 0
				this.questionType.forEach( (item) =>{
					sun += (parseInt(item.score) * parseInt(item.count))
				});
				return sun
			}
		},
		destroyed(){
			/**
			 * 离开当前页面时，移除之前的自定义class类名
			 */
			this.headClassList.remove('hidden-header')
		},
		methods: {
			/**
			 * 关闭图片
			 * @DateTime 2020-04-16T17:40:41+0800
			 * @qiu_m
			 * @return   {[type]}                 [description]
			 */
			 closeViewer() {
			 	this.imagePreview.showViewer = false;
			 	this.imagePreview.previewSrcList = []
			 },
			setCopyTest(obj){

				let success = (res)=>{
					// :to="{path: '/test/knowledge-points', query: {edit: $route.query.id,}}"
					this.$router.push({path: '/test/knowledge-points', query: {edit: res.data, points: 1, copy: this.$route.query.id}})
				};
				let data = {id: this.$route.query.id}
				this.$ajax.post('api/newtest/copy_test', data, {func: {success: success}});
				// this.$ajax.post('api/newtest/copy_test', data, {func: {success:success}})
			},
			/**
			 * 改变试题的平均分
			 * @DateTime 2019-08-17T12:22:03+0800
			 * @param    {[type]}                 val   [description]
			 * @param    {[type]}                 index [description]
			 */
			setTotal(val, obj){
		

				this.testList.question_list.forEach((item, index)=>{
					if (obj.id == item.qt_id ) {
						 item.score = val
						 // console.log(item.score );
					}
				})
			},
			/**
			 * 根据参数请求试卷详情
			 * @DateTime 2019-07-22T17:37:30+0800
			 * @return   {[type]}                 [description]
			 */
			getTestList(){
				let success = (res=>{
					this.testList = res.data;

					if (this.$route.query.points == 2) {

						this.ruleForm.name = this.testList.name;
						this.ruleForm.time = res.data.answer_time
					}else{
						this.ruleForm.name = this.intelligentObj.name;
						this.ruleForm.time = this.intelligentObj.duration;
					}

					this.testList.question_type.forEach( item =>{
						this.questionType.push({
							id: item.id,
							count: item.count,
							name: item.question_type,
							score: (parseInt(item.score)/parseInt(item.count))
						})
					});

				/*	this.$nextTick(()=>{
						//改变试题 img 的 url
						let imgArr = document.querySelectorAll('.preview-conten-subject-c img')
						let baseUrl = sessionStorage.getItem('host_addr');
						for (var i = 0; i < imgArr.length; i++) {
							let _temp = imgArr[i].src
							imgArr[i].src = _temp.replace(location.protocol+'//'+location.host, baseUrl);
						}
					});*/

					this.loading = false;
				});

				let params = {
					user_id: this.$g.user_id,
					id: this.$route.query.id
				};

				this.$ajax({
					url: 'api/newtest/test_detail',
					method: 'get',
					params: params,
					func: {success: success}
				})
			},
			/**
			 * 试卷的试题排序
			 * @DateTime 2019-08-13T15:27:53+0800
			 * @return   {[type]}                 [description]
			 */
			testChang(){
				let [idex, questionList] = [1, []]



				this.testList.question_list.forEach((item, index) =>{
					questionList.push({
						'question_id': item.id,
						'score': item.score,
						'sort': idex++
					})
				});

	

				let success = (res=>{
					this.$message.success(res.msg);
					// this.$router.push({path: '/test/details', query: {id: this.$route.query.id}})

					this.$router.push({path: '/test/test-paper', query: {id: this.$route.query.id, authority: 2}})
				});

	

				let params = {test_id: this.$route.query.id, question_list: questionList};
				this.$ajax.put('api/newtest/change_test', params, {func: {success: success}})
			},
			submitForm(formName) {

				this.$refs[formName].validate((valid) => {
					if (valid) {
						let success = (res =>{
							// this.$message.success(res.msg);
							this.testChang()
							
						});

						let params = {
							create_id: this.$g.user_id,
							id: this.$route.query.id,
							name: this.ruleForm.name,
							answer_time: this.ruleForm.time,
							status: 1,
						};

						this.$ajax({
							url: 'api/newtest/save_test',
							method: 'put',
							data: params,
							func: {success: success}
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			/**
			 * 下载试题
			 * @DateTime 2019-08-02T17:40:31+0800
			 * @return   {[type]}                 [description]
			 */
			downloadFiler(){
			
				return `${this.BASE_URL}/index/test/download_test?id=${this.$route.query.id}&answer=only_test`;
			},
			/**
			 * 返回智慧组卷重新配置试卷
			 * @DateTime 2019-08-03T09:09:33+0800
			 * @return   {[type]}                 [description]
			 */
			goBlck(){
				this.$confirm('重新配置试卷', '提示', {
					cancelButtonText: '取消',
					confirmButtonText: '确定',
					type: 'warning',
					customClass: "test-message"
				}).then(() => {
					this.$message.success('开始重新配置试卷');
					this.$router.push('/test/intelligent')
				}).catch(() => {});
			}
		},

	}
</script>
<style>


</style>